const path = require("path");
const projectName = process.env.PROJECT_NAME;

const createOutput = require("./config/output");
const createAlias = require("./config/alias");
const createCdn = require("./config/cdn");
const createCache = require("./config/cache");
const createNoParse = require("./config/noParse");
const createIgnore = require("./config/ignore");
const createLoader = require("./config/loader");
const createGzip = require("./config/gzip");
const createPerformance = require("./config/performance");
const createOther = require("./config/other");
const plugins = require("./config/plugins");

let config = {};

try {
  config = require(path.resolve(
    __dirname,
    `./projects/${projectName}/vue.config.js`
  ));
} catch (error) {
  console.log("Error reading vue.config.js:", error);
}

const pages = {
  index: {
    entry: `projects/${projectName}/src/main.js`,
    template: `projects/${projectName}/public/index.html`,
    filename: "index.html"
  }
};

module.exports = {
  pages,
  parallel: false,
  lintOnSave: true,
  publicPath: "/",
  productionSourceMap: false,
  outputDir: `projects/${projectName}/dist`,
  configureWebpack: (config) => {
    config.resolveLoader = {
      modules: ["node_modules", "./config/loader"]
    };
    return {
      plugins
    };
  },
  chainWebpack: (config) => {
    Object.keys(pages).forEach((element) => {
      config.plugins.delete(`preload-${element}`); // 删除默认的preload
      config.plugins.delete(`prefetch-${element}`); // 删除默认的prefetch
      config.plugin(`html-${element}`).tap((args) => {
        // args[0].CDN = cdn[isProd ? "build" : "dev"];
        return args;
      });
    });
    // 添加静态资源目录
    config.plugin("copy").use(require("copy-webpack-plugin"), [
      [
        {
          from: path.resolve(__dirname, `projects/${projectName}/public`),
          to: path.resolve(__dirname, projectName),
          toType: "dir",
          ignore: []
        },
        {
          from: path.resolve(__dirname, "projects/common/public"),
          to: path.resolve(__dirname, projectName),
          toType: "dir",
          ignore: []
        }
      ]
    ]);

    // output
    createOutput(config);
    // 配置别名
    createAlias(config);
    // cdn
    createCdn(config);
    // 配置缓存
    createCache(config);
    // noParse
    createNoParse(config);
    // ignore
    createIgnore(config);
    // 解决xss攻击，消除标签之间的空格、font、images、svg、worker
    createLoader(config);
    // gzip
    createGzip(config);
    // 性能监控
    createPerformance(config);
    // other, 修复热更新问题, 首屏发送更少的请求
    createOther(config);
  },
  ...config
};
